/*
 * 后台数据请求服务
 */
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';
import { CacheService } from '../cache.service';
import { NativeService } from '../native.service';

interface ResponseType {
    code: number;
    data: any;
    message: string;
    success: boolean;
}

@Injectable({
    providedIn: 'root',
})
export class InstallService {

    // 本地存储安装进度
    private install;
    // 本地存储数据栈
    private stack;
    // {
    //     'projectId1': {
    //         'areaId1': {
    //             'deviceId1': null
    //         }
    //     },
    //     'projectId2': {
    //         'areaId1': {
    //             'deviceId1': null
    //         }
    //     }
    // };
    public headers: HttpHeaders = new HttpHeaders({
        'Content-Type': 'application/json',
        Ver: 'web_1.0',
        Token: '',
    });


    constructor(
        private http: HttpClient,
        private cache: CacheService,
        private native: NativeService
    ) {
        this.setHeader();
    }

    private setHeader() {
        this.cache.clientToken.subscribe(val => {
            if (val) {
                let ver = 'web_1';
                const ptype = this.native.getPlatformType();
                if (ptype === 'android') {
                    ver = 'android_1.0';
                }
                if (ptype === 'ios') {
                    ver = 'ios_1.0';
                }
                this.headers = new HttpHeaders({
                    Ver: ver,
                    Token: val,
                });
            }
        });
    }

    private sendRequest(
        serverCode,
        apiCode,
        params,
        headertype
    ): Observable<ResponseType> {
        const res = this.cache.getUrl(serverCode, apiCode);
        return new Observable(observer => {
            this.getHeader(headertype).subscribe(headers => {
                this.http
                    .post(res.serviceAddr + res.apiAddr, params, {
                        headers: headers,
                    })
                    .subscribe(val => {
                        observer.next(<ResponseType>val);
                        observer.complete();
                    });
            });
        });
    }

    private getHeader(type): Observable<any> {
        return new Observable(observer => {
            if (type === 'with_token') {
                this.cache.clientToken.subscribe(data => {
                    const keyHeader = new HttpHeaders({
                        'Content-Type': 'application/json',
                        token: data,
                        Ver: 'android_1.0',
                    });
                    observer.next(keyHeader);
                    observer.complete();
                });
            } else {
                observer.next(
                    new HttpHeaders({
                        'Content-Type': 'application/json',
                        Ver: 'android_1.0',
                    })
                );
                observer.complete();
            }
        });
    }


    /**
     * @param projectId 项目id
     * @param areaId 房间id
     * @param deviceId 设备id
     * @param data 安装数据
     */
    saveInstallData(areaId, deviceId, data) {
        const projectId = this.cache.currentProject.projectId;
        this.cache.install.subscribe(res => {
            this.install = res;
            if (this.install) {
                if (this.install[projectId]) {
                    if (this.install[projectId][areaId]) {
                        this.install[projectId][areaId][deviceId] = data;
                    } else {
                        this.install[projectId][areaId] = {};
                        this.install[projectId][areaId][deviceId] = data;
                    }
                } else {
                    this.install[projectId] = {};
                    this.install[projectId][areaId] = {};
                    this.install[projectId][areaId][deviceId] = data;
                }
            } else {
                this.install = {};
                this.install[projectId] = {};
                this.install[projectId][areaId] = {};
                this.install[projectId][areaId][deviceId] = data;
            }
            this.cache.install = this.install;
        });
    }

    /**
    * @param projectId 项目id
    * @param areaId 房间id
    * @param deviceId 设备id
    * @return 安装数据
    */
    getInstallData(projectId, areaId, deviceId?): Observable<any> {
        return new Observable(responseObserver => {
            this.cache.install.subscribe(res => {
                if (res && res[projectId] && res[projectId][areaId]) {
                    if (deviceId !== undefined) {
                        responseObserver.next(res[projectId][areaId][deviceId]);
                    } else {
                        responseObserver.next(res[projectId][areaId]);
                    }
                } else {
                    responseObserver.next(null);
                }
            });
        });
    }


    /**
     * @param projectId 项目id
     * @param areaId 房间id
     * @param deviceId 设备id
     * @param data 安装数据
     */
    saveStack(areaId, data) {
        const projectId = this.cache.currentProject.projectId;
        this.cache.stack.subscribe(res => {
            this.stack = res;
            if (this.stack) {
                if (this.stack[projectId]) {
                    this.stack[projectId][areaId] = data;
                } else {
                    this.stack[projectId] = {};
                    this.stack[projectId][areaId] = data;
                }
            } else {
                this.stack = {};
                this.stack[projectId] = {};
                this.stack[projectId][areaId] = data;
            }
            console.log(this.stack)
            this.cache.stack = this.stack;
        });
    }

    /**
    * @param projectId 项目id
    * @param areaId 房间id
    * @param deviceId 设备id
    * @return 安装数据
    */
    getStack(projectId, areaId): Observable<any> {
        return new Observable(responseObserver => {
            this.cache.stack.subscribe(res => {
                console.log(res)
                if (res && res[projectId] && res[projectId][areaId]) {
                    responseObserver.next(res[projectId][areaId]);
                } else {
                    responseObserver.next(null);
                }
            });
        });
    }


    /**
     * 快速部署_APP获取房间列表
     */
    getAreaList(projectId) {
        const serverCode = 101;
        const apiCode = 103184;
        let reqBody: any;
        reqBody = {
            projectId: projectId
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP获取房间信息
     */
    getAreaInfo(projectId, areaId) {
        const serverCode = 101;
        const apiCode = 103185;
        let reqBody: any;
        reqBody = {
            projectId: projectId,
            areaId: areaId
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
       * 快速部署_APP激活数据栈
       */

    getActivate(areaId, stackId, stackCode) {
        const serverCode = 101;
        const apiCode = 103186;
        let reqBody: any;
        reqBody = {
            areaId: areaId,
            stackId: stackId,
            stackCode: stackCode
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP校验仪表Mudbus或UID是否重复
     */
    checkMeter(areaId, stackId, meterId, pid, modbusAddress) {
        const serverCode = 101;
        const apiCode = 103191;
        let reqBody: any;
        reqBody = {
            areaId: areaId,
            stackId: stackId,
            meterId: meterId,
            pid: pid || 0,
            modbusAddress: modbusAddress
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP仪表激活
     */
    getActivateMeter(stackId, meterId, pid, modbusAddress, deviceParams, addtions) {
        const serverCode = 101;
        const apiCode = 103187;
        let reqBody: any;
        reqBody = {
            stackId: stackId,
            meterId: meterId,
            pid: pid,
            modbusAddress: modbusAddress,
            deviceParams: deviceParams || null,
            addtions: addtions || null
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP获取仪表初始设置
     */
    getInitMeter(meterId) {
        const serverCode = 101;
        const apiCode = 103188;
        let reqBody: any;
        reqBody = {
            meterId: meterId
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP提交仪表初始设置
     */
    sendInitMeter(stackId, meterId, initDatas) {
        const serverCode = 101;
        const apiCode = 103189;
        let reqBody: any;
        reqBody = {
            stackId: stackId,
            meterId: meterId,
            initDatas: initDatas
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP检核仪表
     */
    checkAgain(stackId, meterId, modbusAddress, pid) {
        const serverCode = 101;
        const apiCode = 103190;
        let reqBody: any;
        reqBody = {
            stackId: stackId,
            meterId: meterId,
            modbusAddress: modbusAddress,
            pid: pid
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP获取子传感器选择的采集器列表
     */
    getCollectors(meterId) {
        const serverCode = 101;
        const apiCode = 103193;
        let reqBody: any;
        reqBody = {
            meterId: meterId,
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
      * 快速部署_APP数据栈重装
      */
    clearStack(areaId, stackId, stackCode) {
        const serverCode = 101;
        const apiCode = 103194;
        let reqBody: any;
        reqBody = {
            areaId: areaId,
            stackId: stackId,
            stackCode: stackCode
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }


    /**
     * 快速部署_APP仪表重装
     */
    clearMeter(meterId) {
        const serverCode = 101;
        const apiCode = 103195;
        let reqBody: any;
        reqBody = {
            meterId: meterId,
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
     * 快速部署_APP保存安装进度
     */
    saveProgress(step, bType, bId, userId, card, address, startTime, endTime, deployFiles, deployParams, datas) {
        const serverCode = 101;
        const apiCode = 103196;
        let reqBody: any;
        reqBody = {
            step: step,
            bType: bType,
            bId: bId,
            userId: userId,
            card: card,
            address: address,
            startTime: startTime,
            endTime: endTime,
            deployFiles: deployFiles,
            deployParams: deployParams,
            datas: datas
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    /**
         * 快速部署_APP保存安装获取
         */
    getProgress(bType, bId) {
        const serverCode = 101;
        const apiCode = 103197;
        let reqBody: any;
        reqBody = {
            bType: bType,
            bId: bId
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

    getdeviceParams(deviceTypeCode, deviceParameterCode): Observable<Object> {
        const serverCode = 101;
        const apiCode = 101054;
        let reqBody: any;
        reqBody = {
            deviceTypeCode: deviceTypeCode,
            deviceParameterCode: deviceParameterCode
        };
        return this.sendRequest(serverCode, apiCode, reqBody, 'with_token');
    }

}
